'use client'
import React, {useEffect, useState} from "react";
import SearchForm from "@/app/home/system/app/SearchForm";
import {Security} from "@/app/lib/security";
import {Button, message, PaginationProps, Space, Switch, Table, TableProps, Tooltip} from "antd";
import {PageResult, postFetch} from "@/app/lib/HttpProtocol";
import {Disabled} from "@/app/lib/common";
import AddModal from "@/app/home/system/app/AddModal";
import EditModal from "@/app/home/system/app/EditModal";
import DeleteModal from "@/app/components/common/DeleteModal";
import {User} from "@/app/lib/user";
import UserDetailModal from "@/app/home/system/user/DetailModal";
import DetailModal from "@/app/home/system/app/DetailModal";
import {func} from "prop-types";
import AppUserDrawer from "@/app/home/system/app/AppUserDrawer";

const styleSize = "middle"

const apis = {
  appPageApi:'/app/page',
  appAddApi:'/app/add',
  appEditApi:'/app/update',
  appDeleteApi:'/app/delete',
  appEnableApi:'/app/enable',
  appDisableApi:'/app/disable',
  appUserApi: '/app/user/page'
}
const initPage:PageResult = {total:0,list:[]}
const initParams:any = {pageNum:1,pageSize:20};
async function loadAppPage(params:any){
  return await postFetch(apis.appPageApi,params);
}

function addKey(apps:any[]){
  return apps.map(a => {
    Object.assign(a,{key:a.id});
    return a;
  })
}

// @ts-ignore
function getColumns(showEdit,showDelete,showDetail,showAppUser):TableProps<Any>['columns']{
  return [
    {
      title:'应用名',
      dataIndex:'appname',
      key:'appname',
      width:150,
    },{
      title:'应用显示名',
      dataIndex:'appTitle',
      key:'appTitle',
      width:150,
    },{
      title:'图标',
      dataIndex:'icon',
      key:'icon',
      width:50,
      render:(d) => d?<img src={d} alt="avatar" style={{ maxWidth:30,maxHeight:24,objectFit:"cover"}} />:""
    },{
      title:'地址',
      dataIndex:'route',
      key:'route',
      width:200,
      ellipsis: {
        showTitle: false,
      },
      render:(d) => <Tooltip placement="topLeft" title={d}>{d}</Tooltip>,
    },{
      title:'描述',
      dataIndex:'description',
      key:'description',
      width:200,
      ellipsis: {
        showTitle: false,
      },
      render:(d) => <Tooltip placement="topLeft" title={d}>{d}</Tooltip>,
    },{
      title:'状态',
      dataIndex:'disabled',
      key:'disabled',
      width:100,
      render:(d,record) => <Switch checkedChildren="开启" unCheckedChildren="关闭" defaultChecked={d == 0} onChange={(checked) => changeDisabled(record,checked?0:1)}/>,
    },{
      title:'操作',
      key:'action',
      render:(_,record) =>(
        <Space size="middle">
          <Security perm={apis.appEditApi}><Button size={"small"} type="primary" onClick={() => showEdit(record)}>编辑</Button></Security>
          <Security perm={apis.appDeleteApi}><Button size={"small"} type="primary" onClick={() => showDelete(record)}>删除</Button></Security>
          <Security perm={apis.appPageApi}><Button size={"small"} type="primary" onClick={() => showDetail(record)}>详情</Button></Security>
          <Security perm={apis.appUserApi}><Button size={"small"} type="primary" onClick={() => showAppUser(record)}>可见用户</Button></Security>
        </Space>
      )
    }
  ];
}

const changeDisabled = function(app:any,disabled:number){
  if(disabled == 0){
    postFetch(apis.appEnableApi,app).then(id　=> {
      message.success("操作成功")
    })
  }
  if(disabled == 1){
    postFetch(apis.appDisableApi,app).then(id　=> {
      message.success("操作成功")
    })
  }
}

export default function Home() {

  const [page,setPage] = useState(initPage);
  const [params,setParams] = useState(initParams)
  useEffect(() => {
    loadPage();
  },[])
  const loadPage = () => {
    loadAppPage(params).then(page => {
      // @ts-ignore
      setPage(page);
    })
  }
  const pageChange: PaginationProps['onChange'] = (pageNum,pageSize) => {
    params.pageNum = pageNum;
    params.pageSize = pageSize;
    setParams({...params})
    loadPage();
  };
  const onSearchFinish = (values: any) => {
    Object.assign(params,values)
    setParams({...params})
    loadPage();
  };
  
  const [select,setSelect] = useState<any>({})
  const [modalStatus,setModalStatus] =
    useState({add:false,edit:false,delete:false,detail:false, appUser:false
    })
  function showEditModal(app:any) {
    setSelect({...app});
    modalStatus.edit = true;
    setModalStatus({...modalStatus})
  }
  function showDeleteModal(app:any){
    setSelect({...app});
    modalStatus.delete = true;
    setModalStatus({...modalStatus})
  }
  function showAddModal(){
    modalStatus.add = true;
    setModalStatus({...modalStatus})
  }
  function showDetailModal(app:any){
    setSelect({...app});
    modalStatus.detail = true;
    setModalStatus({...modalStatus})
  }
  function showAppUserDrawer(app:any){
    setSelect({...app});
    modalStatus.appUser = true;
    setModalStatus({...modalStatus})
  }
  function handleAddOk(app:any){
    postFetch(apis.appAddApi,app).then(id　=> {
      message.success("操作成功")
      modalStatus.add = false;
      setModalStatus({...modalStatus})
      loadPage();
    })
  }
  function  handleAddCancel(){
    modalStatus.add = false;
    setModalStatus({...modalStatus})
  }
  function handleEditOk(app:any){
    Object.assign(select,app);
    postFetch(apis.appEditApi,select).then(id　=> {
      message.success("操作成功")
      modalStatus.edit = false;
      setModalStatus({...modalStatus})
      loadPage();
    })
  }
  function  handleEditCancel(){
    modalStatus.edit = false;
    setModalStatus({...modalStatus})
  }
  function handleDeleteOk(app:any){
    modalStatus.delete = false;
    setModalStatus({...modalStatus})
    postFetch(apis.appDeleteApi, {id:app.id}).then(id　=> {
      message.success("操作成功")
      loadPage();
    })
  }
  function  handleDeleteCancel(){
    modalStatus.delete = false;
    setModalStatus({...modalStatus})
  }

  function onDetailClose(){
    modalStatus.detail = false;
    setModalStatus({...modalStatus})
  }
  function onAppUserClose(){
    modalStatus.appUser = false;
    setModalStatus({...modalStatus})
  }
  return (
    <>
      <SearchForm onSearchFinish={onSearchFinish}/>
      <div style={{ marginTop: 16 }}>
        <Security perm={apis.appAddApi}><Button type="primary" onClick={showAddModal} size={"small"}>
          添加
        </Button></Security>
      </div>
      <Table columns={getColumns(showEditModal,showDeleteModal,showDetailModal,showAppUserDrawer)}
             dataSource={addKey(page.list)} size={styleSize}
             scroll={{ y: 340 }}
             pagination={{total: page.total, showSizeChanger: true, onChange: pageChange,pageSize:params.pageSize,current:params.pageNum}}
      />
      {!modalStatus.add ?<></>: <AddModal open={true} onAddOk={handleAddOk} onAddCancel={handleAddCancel} />}
      {!modalStatus.edit ?<></>: <EditModal open={true} onEditOk={handleEditOk} onEditCancel={handleEditCancel} app={select}/>}
      {!modalStatus.delete && select ?<></>: <DeleteModal open={true} onDeleteOk={handleDeleteOk} onDeleteCancel={handleDeleteCancel} obj={select} />}
      {!modalStatus.detail && select ?<></>: <DetailModal open={true} onClose={onDetailClose} app={select}/>}
      {!modalStatus.appUser && select ?<></>: <AppUserDrawer open={true} onClose={onAppUserClose} app={select}/>}

    </>
  );
}
